import time
from flask import Blueprint,Response, request
import numpy as np
import cv2
from exts import db_conn
import datetime

bp = Blueprint("fb",__name__,url_prefix="/fb")

class HistoryRecord:
    def __init__(self, id, speed, create_time):
        self.id = id
        self.speed = speed
        self.create_time = create_time

    def to_json(self):
        return {
            "id": self.id,
            "speed": self.speed,
            "create_time": self.create_time
        }

@bp.route('/test')
def get_test():
    return "test"

@bp.route('/history', methods=["GET","POST"])
def get_history_speed():
    cursor = db_conn.cursor()
    cursor.execute("SELECT * FROM history")
    result = cursor.fetchall()
    cursor.close()
    # "*" 表示解包，将元组解包成参数，传入构造函数
    result = [HistoryRecord(*r).to_json() for r in result]
    print(result)
    return result

# example: http://127.0.0.1:5555/file/height/617.22
@bp.route('/height/<height>')
def get_speed(height):
    return  {
        "height":1,
        "area":2,
        "speed":3,
        "runoff":4
    }

@bp.route('/test2')
def fb_speed():

    cap = cv2.VideoCapture('http://113.54.7.17:81/rtp/44010200491310000024_44010200491310000024/hls.m3u8')

    # 获取视频的帧率
    fps = cap.get(cv2.CAP_PROP_FPS)
    # 获取视频的宽度 和 高度
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # 读取第一帧
    ret, frame1 = cap.read()
    prev_gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)

    # 定义HSV颜色空间
    hsv = np.zeros_like(frame1)
    hsv[..., 1] = 255
    speed_i = 0
    speed_sum = 0
    while True:
        ret, frame2 = cap.read()
        if not ret:
            break
        gray = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
        gray[gray>240] = 0
        gray[gray<170] = 0
        # 计算光流 https://blog.csdn.net/weixin_45224869/article/details/105100996
        flow = cv2.calcOpticalFlowFarneback(prev_gray, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)

        # 计算光流的幅度和方向
        magnitude, angle = cv2.cartToPolar(flow[..., 0], flow[..., 1])

        # 设置HSV颜色空间的饱和度值
        hsv[..., 0] = angle * 180 / np.pi / 2
        hsv[..., 2] = cv2.normalize(magnitude, None, 0, 255, cv2.NORM_MINMAX)

        # 转换回BGR颜色空间
        # bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
        # 计算幅度评价
        # magnitude_mean = magnitude[magnitude>5].mean()
        magnitude_mean = magnitude[(magnitude>5) & (magnitude<25)].mean()
        # 计算速度
        speed = magnitude_mean /width * fps *15
        # print(f'magnitude_mean: {magnitude_mean} p/s',f'Speed: {speed} m/s')
        print(speed)
        speed_sum += speed
        speed_i += 1
        if speed_i == 25:
            break

        # 更新前一帧
        prev_gray = gray
    
    speed_mean = speed_sum/speed_i

    # insert
    cursor = db_conn.cursor()

    # 当前时间，python 拼接字符串
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    cursor.execute("INSERT INTO history (speed, create_time) VALUES ({}, '{}')".format(speed_mean, now))
    db_conn.commit()
    cursor.close()

    return str(speed_mean)


